package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.Polyline;
import com.amap.api.maps2d.model.PolylineOptions;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.AttendanceDetail;
import com.isunland.managesystem.entity.AttendanceListOriginal;
import com.isunland.managesystem.entity.AttendanceQueryContent;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import org.json.JSONException;

/**
 * Created by lenovo on 2016/11/18.
 */
public class AttendanceMapFragment extends Fragment implements View.OnClickListener {
  //查询传递的参数
  protected static final String EXTRA_QUERY =
      "com.isunland.managesystem.ui.AttendanceMapFragment.extra_query";
  protected static final String EXTRA_TYPE =
      "com.isunland.managesystem.ui.AttendanceMapFragment.EXTRA_TYPE";
  private MapView mMapView;
  private AMap aMap;
  private ArrayList<AttendanceDetail> mList;
  private LinearLayout mllMapHeader;
  private TextView mtvEndDate;
  private TextView mtvStartDate;
  private TextView mtvType;

  protected static final String IN = "in";
  protected static final String OUT = "out";
  protected static final String KEEP = "keep";
  private static final int REQUEST_QUERY = 0;
  private BaseVolleyActivity mActivity;
  private AttendanceQueryContent mqueryContent;
  private String checkType = IN;
  private String begincheckTime;
  private String endcheckTime;
  private String name;
  private String jobNos;

  public AMapLocationClient mLocationClient;
  private MyLocationListener mLocationListener;
  List<LatLng> mlatLngs = new ArrayList<>();

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (null != actionBar) {
      actionBar.setTitle(R.string.sign_map);
      actionBar.setDisplayHomeAsUpEnabled(true);
    }

    CurrentUser mUser = CurrentUser.newInstance(getActivity());
    name = mUser.getRealName();
    jobNos = mUser.getJobNumber();
    checkType = IN;
    begincheckTime = MyDateUtil.getFirstDay();
    endcheckTime = MyDateUtil.getLastDay();
    volleyPostList();
    super.onCreate(savedInstanceState);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_attendance_map, container, false);
    mllMapHeader = (LinearLayout) view.findViewById(R.id.ll_mapHeader);
    mtvType = (TextView) view.findViewById(R.id.tv_name_signHeader);
    mtvStartDate = (TextView) view.findViewById(R.id.tv_startDate_signHeader);
    mtvEndDate = (TextView) view.findViewById(R.id.tv_endDate_signHeader);
    mMapView = (MapView) view.findViewById(R.id.mv_map);
    //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
    mMapView.onCreate(savedInstanceState);
    //初始化地图变量
    if (aMap == null) {
      aMap = mMapView.getMap();
    }
    updateHeader();
    mllMapHeader.setOnClickListener(this);
    return view;
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_query, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_query:
        startQueryActivity();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void startQueryActivity() {
    mqueryContent =
        new AttendanceQueryContent(name, jobNos, checkType, begincheckTime, endcheckTime);
    Intent query = new Intent(getActivity(), AttendanceQueryActivity.class);
    query.putExtra(EXTRA_QUERY, mqueryContent);
    startActivityForResult(query, REQUEST_QUERY);
  }

  private void volleyPostList() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SIGN_LIST);
    HashMap<String, String> params = new HashMap<>();
    params.put("page", "1");
    params.put("rows", "1000");
    params.put("jobNos", jobNos);
    params.put("checkType", checkType);
    params.put("begincheckTime", begincheckTime);
    params.put("endcheckTime", endcheckTime);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        AttendanceListOriginal attendanceListOriginal =
            new Gson().fromJson(arg0, AttendanceListOriginal.class);
        List<AttendanceDetail> attendanceDetail = attendanceListOriginal.getList();
        if (mList == null) {
          mList = new ArrayList<>();
        }
        mList.clear();
        mList.addAll(attendanceDetail);
        initMap(mList);//地图缩放级别
        initMark();
      }
    });
  }

  private void initMap(List<AttendanceDetail> mList) {
    for (int i = 0; i < mList.size(); i++) {
      if (!TextUtils.isEmpty(mList.get(i).getLatitude()) && !TextUtils.isEmpty(
          mList.get(i).getLongitude())) {
        double lat = Double.parseDouble(mList.get(i).getLatitude());
        double lon = Double.parseDouble(mList.get(i).getLongitude());
        CameraUpdate cameraUpdate =
            CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(lat, lon),//新的中心点坐标
                15, //新的缩放级别
                0, //俯仰角0°~45°（垂直与地图时为0）
                0  ////偏航角 0~360° (正北方为0)
            ));
        aMap.animateCamera(cameraUpdate);
        break;
      }
    }
  }

  private void updateHeader() {
    if (IN.equalsIgnoreCase(checkType)) {
      mtvType.setText("类型<" + "签到" + ">");
    } else if (OUT.equalsIgnoreCase(checkType)) {
      mtvType.setText("类型<" + "签退" + ">");
    } else if (KEEP.equalsIgnoreCase(checkType)) {
      mtvType.setText("类型<" + "外勤" + ">");
    }
    mtvStartDate.setText(begincheckTime);
    mtvEndDate.setText(endcheckTime);
  }

  private void initMark() {
    if (IN.equalsIgnoreCase(checkType) || OUT.equalsIgnoreCase(checkType)) {
      //画点标记
      paintMark();
    } else {
      //画折线
      paintLine();
    }
  }

  private void paintLine() {
    //        List<LatLng> latLngs = new ArrayList<LatLng>();
    //        latLngs.add(new LatLng(39.999391, 116.135972));
    //        latLngs.add(new LatLng(39.898323, 116.057694));
    //        initPolyline(latLngs);
    //        List<LatLng> latLngs1 = new ArrayList<LatLng>();
    //        latLngs1.add(new LatLng(39.900430, 116.265061));
    //        latLngs1.add(new LatLng(39.955192, 116.140092));
    //        initPolyline(latLngs1);

    List<LatLng> latLngs = new ArrayList<>();
    String outId = "";
    boolean ifFirst = true;//是否是一条线的开始
    for (int i = 0; i < mList.size(); i++) {
      if (!TextUtils.isEmpty(mList.get(i).getOutId())) {
        if (ifFirst) {
          outId = mList.get(i).getOutId();
        }
        //当id 相同时
        if (outId.equalsIgnoreCase(mList.get(i).getOutId())) {
          if (!TextUtils.isEmpty(mList.get(i).getLatitude()) && !TextUtils.isEmpty(
              mList.get(i).getLongitude())) {
            double lat = Double.parseDouble(mList.get(i).getLatitude());
            double lon = Double.parseDouble(mList.get(i).getLongitude());
            latLngs.add(new LatLng(lat, lon));
            ifFirst = false;
          }
        } else {
          if (latLngs != null && latLngs.size() != 0) {
            initPolyline(latLngs);
            latLngs.clear();
            ifFirst = true;
          }
        }
      } else {
        if (latLngs != null && latLngs.size() != 0) {
          initPolyline(latLngs);
          latLngs.clear();
          ifFirst = true;
        }
      }
    }
    if (latLngs.size() > 0) {
      initPolyline(latLngs);
    }
  }

  private void initPolyline(List<LatLng> latLngs) {
    Marker start = aMap.addMarker(new MarkerOptions().position(
        new LatLng(latLngs.get(latLngs.size() - 1).latitude,
            latLngs.get(latLngs.size() - 1).longitude))
        .title("起点")
        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
    Marker finish = aMap.addMarker(
        new MarkerOptions().position(new LatLng(latLngs.get(0).latitude, latLngs.get(0).longitude))
            .title("终点")
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
    Polyline polyline = aMap.addPolyline(new PolylineOptions().addAll(latLngs)
        .width(5)
        .color(Color.argb(255, new Random().nextInt(256), new Random().nextInt(256),
            new Random().nextInt(256))));
    start.showInfoWindow();
    finish.showInfoWindow();
  }

  private void paintMark() {
    for (int i = 0; i < mList.size(); i++) {
      if (!TextUtils.isEmpty(mList.get(i).getLatitude()) && !TextUtils.isEmpty(
          mList.get(i).getLongitude())) {
        double lat = Double.parseDouble(mList.get(i).getLatitude());
        double lon = Double.parseDouble(mList.get(i).getLongitude());
        LatLng latLng = new LatLng(lat, lon);
        Marker marker = aMap.addMarker(new MarkerOptions().position(latLng)
            .title(mList.get(i).getLocation())
            .snippet(MyDateUtil.dateToString(new Date(mList.get(i).getCheckTime()),
                MyDateUtil.TYPE_ALL)));
        if (OUT.equalsIgnoreCase(checkType)) {
          marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
        }
      }
    }
  }

  @Override public void onDestroy() {
    super.onDestroy();
    //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
    mMapView.onDestroy();
  }

  @Override public void onResume() {
    super.onResume();
    //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
    mMapView.onResume();
  }

  @Override public void onPause() {
    super.onPause();
    //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
    mMapView.onPause();
  }

  @Override public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
    mMapView.onSaveInstanceState(outState);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_QUERY) {
      mqueryContent = (AttendanceQueryContent) data.getSerializableExtra(EXTRA_QUERY);
      name = mqueryContent.getName();
      jobNos = mqueryContent.getJobNos();
      checkType = mqueryContent.getCheckType();
      begincheckTime = mqueryContent.getBegincheckTime();
      endcheckTime = mqueryContent.getEndcheckTime();
      updateHeader();
      aMap.clear();// 清理之前的图标

      //            if (KEEP.equalsIgnoreCase(checkType)) {
      //                CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(
      //                        new LatLng(40.041448, 116.30837),//新的中心点坐标
      //                        15, //新的缩放级别
      //                        0, //俯仰角0°~45°（垂直与地图时为0）
      //                        0  ////偏航角 0~360° (正北方为0)
      //                ));
      //                aMap.animateCamera(cameraUpdate);
      //                getLocation();
      //            } else {
      volleyPostList();
      //            }
    }
  }

  private void getLocation() {
    mLocationListener = new MyLocationListener();
    mLocationClient = new AMapLocationClient(getActivity());
    AMapLocationClientOption locationOption = new AMapLocationClientOption();
    // 设置定位模式为高精度模式
    locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
    locationOption.setInterval(3000);

    // 设置定位监听
    mLocationClient.setLocationListener(mLocationListener);
    // 设置定位参数
    mLocationClient.setLocationOption(locationOption);
    // 启动定位
    mLocationClient.startLocation();
  }

  @Override public void onClick(View view) {
    switch (view.getId()) {
      case R.id.ll_mapHeader:
        startQueryActivity();
        break;
    }
  }

  public class MyLocationListener implements AMapLocationListener {

    @Override public void onLocationChanged(AMapLocation location) {

      if (location == null || location.getErrorCode() != 0) {
        return;
      }
      double latitude = location.getLatitude();
      double longtitude = location.getLongitude();
      mlatLngs.add(new LatLng(latitude, longtitude));
      Log.i("外勤location====", "latitude=" + latitude + ",longtitude=" + longtitude);
      if (mlatLngs.size() >= 0) {
        aMap.clear();
        Marker marker1 = aMap.addMarker(new MarkerOptions().position(
            new LatLng(mlatLngs.get(0).latitude, mlatLngs.get(0).longitude)).title("起点"));
        Marker marker = aMap.addMarker(new MarkerOptions().position(
            new LatLng(mlatLngs.get(mlatLngs.size() - 1).latitude,
                mlatLngs.get(mlatLngs.size() - 1).longitude))
            .title("经度=" + latitude)
            .snippet("纬度=" + longtitude)
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
        Polyline polyline =
            aMap.addPolyline(new PolylineOptions().addAll(mlatLngs).width(5).color(Color.RED));
      }
    }
  }

  //    public static AttendanceMapFragment newInstance(ArrayList<AttendanceDetail> mList, String type) {
  //        AttendanceMapFragment mfragment = new AttendanceMapFragment();
  //        Bundle bundle = new Bundle();
  //        bundle.putSerializable(AttendanceListFragment.EXTRA_QUERY, mList);
  //        bundle.putSerializable(EXTRA_TYPE, type);
  //        mfragment.setArguments(bundle);
  //        return mfragment;
  //    }
}
